package com.example.backend.repository;

import com.example.backend.domain.entity.SystemLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;
import java.util.List;

/**
 * 系统日志Repository
 */
public interface SystemLogRepository extends JpaRepository<SystemLog, Long> {
    
    // 根据级别查找日志
    Page<SystemLog> findByLevel(String level, Pageable pageable);
    
    // 根据分类查找日志
    Page<SystemLog> findByCategory(String category, Pageable pageable);
    
    // 根据用户查找日志
    Page<SystemLog> findByUser_Id(Long userId, Pageable pageable);
    
    // 根据时间范围查找日志
    Page<SystemLog> findByCreatedAtBetween(Instant start, Instant end, Pageable pageable);
    
    // 复合查询
    Page<SystemLog> findByLevelAndCategory(String level, String category, Pageable pageable);
    
    // 搜索日志
    @Query("SELECT l FROM SystemLog l WHERE " +
           "(:level IS NULL OR l.level = :level) AND " +
           "(:category IS NULL OR l.category = :category) AND " +
           "(:keyword IS NULL OR l.message LIKE %:keyword% OR l.action LIKE %:keyword%) AND " +
           "(:startDate IS NULL OR l.createdAt >= :startDate) AND " +
           "(:endDate IS NULL OR l.createdAt <= :endDate)")
    Page<SystemLog> searchLogs(@Param("level") String level,
                              @Param("category") String category,
                              @Param("keyword") String keyword,
                              @Param("startDate") Instant startDate,
                              @Param("endDate") Instant endDate,
                              Pageable pageable);
    
    // 统计日志数量
    long countByLevel(String level);
    long countByCategory(String category);
    long countByCreatedAtBetween(Instant start, Instant end);
    
    // 获取所有级别
    @Query("SELECT DISTINCT l.level FROM SystemLog l ORDER BY l.level")
    List<String> findAllLevels();
    
    // 获取所有分类
    @Query("SELECT DISTINCT l.category FROM SystemLog l ORDER BY l.category")
    List<String> findAllCategories();
}
